package work.person.groups;

import work.config.Constant;
import work.fram.AutoLogger;
import work.fram.FileGroup;
import work.getter.Dict;
import work.getter.TableFiledMapping;
import work.utils.IdCardFormat;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


//处理主表数据
public abstract class AbstractTableHandler extends FileGroup {

    private String[] excelFiles;

    private Map<String, String> nameCodeMap;

    private String tableName;

    public String getTableName() {
        return tableName;
    }

    protected void setName(String name) {//表字段

        tableName = TableFiledMapping.getCodeByName(name);

        if (tableName == null) {
            throw new Error("无法找到表:" + name);
        }

        Map<String, String> map = TableFiledMapping.getMapByName(name);
        if (map != null) {
            map.forEach(this::map);
        }
    }

    protected AbstractTableHandler() {
    }

    protected void setNameCodeMap(Map<String, String> nameCodeMap) {
        this.nameCodeMap = nameCodeMap;
    }

    protected void setExcelFiles(String... excelFiles) {
        this.excelFiles = excelFiles;
    }


    //可以断定一定有姓名
    private boolean check(String name, String idcard, File file) {//

        return true;
    }

    //将字段映射为字典值
    protected void mappingFieldDict(Map<String, String> map) {

        List<String> wr = new ArrayList<>();

        map.forEach((k, v) -> {
            if (nameCodeMap != null) {

                //获取字典类型名称
                String type = nameCodeMap.get(k);
                if (type != null) {
                    String code = Dict.mapValueToCode(type, v);
                    if (code == null) {
                        wr.add(k);
                    } else {
                        map.put(k, code);
                    }
                }
            }
        });
        for (String s : wr) {
            map.remove(s);
        }
    }

    //映射字段
    public void handleFiled(Map<String, String> map) {
        mappingFieldDict(map);
    }

    @Override
    public String[] names() {
        return excelFiles;
    }

    @Override
    public void afterMapping(Map<String, String> map, String name, String idcard, File file) {
/*
        if (!check(name, idcard, file)) {
            return;
        }*/

        String ic = map.get("idcard");
        if (ic == null) {
            AutoLogger.getINTERFACE().writeLine(getTableName() + "没有找到身份证号字段", file.getAbsolutePath().replace(Constant.work.getAbsolutePath(), ""));
            return;
        }

        ic = IdCardFormat.format(ic);
        map.put("idcard", ic);

        handleFiled(map);
        afterHandle(map);
    }

    public abstract void afterHandle(Map<String, String> map);

}
